//
//  ObjectViewController.m
//  IntimateGift
//
//  Created by 张科 on 14-12-20.
//  Copyright (c) 2014年 蔡宏业. All rights reserved.
//

#import "ObjectViewController.h"
#import "CategoryCell.h"
#define CATEGORY @"recategory"
#import "NetHandler.h"
#import "UIImageView+WebCache.h"
#import "WebViewController.h"
#import "DetailsViewController.h"
#import "AllGroup.h"
#import "UIScrollView+Extension.h"
#import "UIScrollView+MJRefresh.h"
@interface ObjectViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)NSMutableArray *categoryArr;
@property(nonatomic, retain)UITableView *categoryTableView;
@property(nonatomic, retain)NSMutableArray *arr;
@property(nonatomic, assign)NSInteger num;


@end

@implementation ObjectViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.num = 12;
    }
    return self;
}


- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)dealloc
{
    [_arr release];
    [_categoryArr release];
    [_categoryTableView release];
    [_group release];
    [super dealloc];
}

- (void)handleData
{
    
    
    NSString *str = [[NSString alloc] initWithFormat:@"http://api.liwushuo.com/v1/channels/%@/items?limit=12&offset=0", self.group.Groupid];
    //NSLog(@"%@", self.group.reallyId);
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
            NSError *error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            NSDictionary *detailDic = [NSDictionary dictionary];
            detailDic = [result objectForKey:@"data"];
            NSArray * detailArr = [detailDic objectForKey:@"items"];
            self.arr = [NSMutableArray array];
            for (NSDictionary *dicTemp in detailArr) {
                WebViewDetail *group = [[WebViewDetail alloc] initWithDictionary:dicTemp];
                [self.arr addObject:group];
                
            }
        [self installcategorytableView];
        [self.categoryTableView reloadData];
        [self setupRefresh];
    }];
    

}

- (void)installcategorytableView
{
     self.categoryTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style: UITableViewStyleGrouped];
    [self.view addSubview:self.categoryTableView];
    self.categoryTableView.delegate = self;
    self.categoryTableView.dataSource = self;
    [self.categoryTableView registerClass:[CategoryCell class] forCellReuseIdentifier:CATEGORY];
    [_categoryTableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        return self.arr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:CATEGORY];
    WebViewDetail *group = [self.arr objectAtIndex:indexPath.row];
    cell.title.text = group.title;
    NSString *str = [group.cover_image_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    [cell.cover_image setImageWithURL:url];
    cell.likes_count.text = group.likes_count;
    return cell;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.group.name;

    [self handleData];
   
   
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailsViewController *detVC = [[DetailsViewController alloc] init];
    detVC.mark = 2;
//    WebViewDetail *webDetail = [self.arr objectAtIndex:indexPath.row];
//    detVC.webDeatil = webDetail;
//    
    [self.navigationController pushViewController:detVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.categoryTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.categoryTableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.categoryTableView addFooterWithTarget:self action:@selector(footerRereshing)];
}


- (void)headerRereshing
{
    
    NSString *str = [[NSString alloc] initWithFormat:@"http://api.liwushuo.com/v1/channels/%@/items?limit=12&offset=0", self.group.Groupid];
    //NSLog(@"%@", self.group.reallyId);
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *detailDic = [NSDictionary dictionary];
        detailDic = [result objectForKey:@"data"];
        NSArray * detailArr = [detailDic objectForKey:@"items"];
        [self.arr removeAllObjects];
//        self.arr = [NSMutableArray array];
        for (NSDictionary *dicTemp in detailArr) {
            WebViewDetail *group = [[WebViewDetail alloc] initWithDictionary:dicTemp];
            [self.arr addObject:group];
            
        }
//        [self installcategorytableView];
        [self.categoryTableView reloadData];
    }];

    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.categoryTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.categoryTableView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    NSString *str = [[NSString alloc] initWithFormat:@"http://api.liwushuo.com/v1/channels/%@/items?limit=12&offset=%ld", self.group.Groupid, (long)self.num];
    //NSLog(@"%@", self.group.reallyId);
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        NSDictionary *detailDic = [NSDictionary dictionary];
        detailDic = [result objectForKey:@"data"];
        NSArray * detailArr = [detailDic objectForKey:@"items"];
//        self.arr = [NSMutableArray array];
        for (NSDictionary *dicTemp in detailArr) {
            WebViewDetail *group = [[WebViewDetail alloc] initWithDictionary:dicTemp];
            [self.arr addObject:group];
            
        }
//        [self installcategorytableView];
        self.num = self.num + 12;
    }];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.categoryTableView reloadData];
        [self.categoryTableView footerEndRefreshing];
    });
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
